package day01;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Random;
import java.util.Scanner;

//import java.util.List;


/**
 * 记单词程序
 */
public class StudyEnglish_2 {
    public static  String parameter;


    /**
     * 进入记单词
     * @throws IOException
     */
    public static void EnterBT() throws IOException   {
        File fileE = new File("./study/English.txt"); //链接单词
        FileInputStream InEnglish = new FileInputStream(fileE); //链接单词
        File fileC = new File("./study/Chinese.txt"); //链接释义
        FileInputStream InChinese = new FileInputStream(fileC); //链接中文释义

        Scanner scanner = new Scanner(System.in);
        /**
         * 随机输出一个单词
         */
        long lenE = fileE.length();
        byte[] subsE = new byte[(int) lenE];

        InEnglish.read(subsE);
        /**
         * 对应释义
         */
        long lenC = fileC.length();
        byte[] subsC = new byte[(int) lenC];
        InChinese.read(subsC);

        String lineE = new String(subsE, StandardCharsets.UTF_8); //英语转字符串
        String lineC = new String(subsC, StandardCharsets.UTF_8); //释义转字符串

        String[] arrE = lineE.split(",");//分隔字符串
        String[] arrC = lineC.split("，");//分隔字符串

        Random random = new Random();

        while (true) {
            int index = random.nextInt(arrE.length);
            JF();
//            sourceE.setText("经过计算，你的年龄是:"+text.getText()+"岁");
            System.out.println("单词：" + arrE[index]);
            System.out.print("请输入中文释义：");
            String userEnglish = scanner.nextLine();
            if (userEnglish.equals("q")) {
                System.out.println("已退出");
//                        quit =false;
                break; //如果输入q，就直接退出
            }
            if (userEnglish.equals(arrC[index])) {
                System.out.println("输入正确！");
            } else {
                System.out.println("错误！");
            }
        }
    }

    /**
     * 输入状态
     * @param
     * @throws IOException
     */
    public static void ChineseWr()throws IOException{
        //            File fileE1 = new File("./study/English.txt");
        FileOutputStream OutEnglish = new FileOutputStream("./study/English.txt", true);
//                File fileC1 = new File("./study/English.txt");
        FileOutputStream OutChinese = new FileOutputStream("./study/Chinese.txt", true);
        Scanner scanner1 = new Scanner(System.in);
        //编辑状态

        while (true) {
            System.out.print("请输入单词：");
            String word1 = scanner1.nextLine();
            if ("q".equals(word1)) {
                System.out.println("已退出编辑状态！");
                break;
            } else {
                OutEnglish.write(word1.getBytes(StandardCharsets.UTF_8));
                OutEnglish.write(",".getBytes(StandardCharsets.UTF_8));
                System.out.println("已存入单词数据库！");
            }
            /**
             * 开始输入中文
             */
            while (true) {
                System.out.print("请输入" + word1 + "的中文释义：");
                String word2 = scanner1.nextLine();
                String zone = "[a-zA-Z0-9_]+"; //正则表达式判断----------- zone：区域
                boolean match = word2.matches(zone);
                if (!match) {
                    OutChinese.write(word2.getBytes(StandardCharsets.UTF_8));
                    OutChinese.write("，".getBytes(StandardCharsets.UTF_8));
                    System.out.println("已存入中文释义数据库！");

                    break;
                } else {
                    System.out.println("请不要输入奇奇怪怪的例如：字符字母数字！！！");
                    continue;
                }
            }
        }
    }

    /**
     *将读取到的文件保存
     */
    public static  void FileSave() throws IOException {
        FileOutputStream OutEnglish = new FileOutputStream("./study/English.txt", true);
        FileOutputStream OutChinese = new FileOutputStream("./study/Chinese.txt", true);
//        Scanner scanner1 = new Scanner(System.in);
//        String word2 = scanner1.nextLine();
//        OutChinese.write(word2.getBytes(StandardCharsets.UTF_8));
//        OutChinese.write("，".getBytes(StandardCharsets.UTF_8));
//        OutEnglish.write(word2.getBytes(StandardCharsets.UTF_8));
//        OutEnglish.write("，".getBytes(StandardCharsets.UTF_8));
        OutChinese.flush();//强制清理
        OutEnglish.flush();//强制清理
        System.out.println("已存入数据库！");
        OutEnglish.close();
        OutChinese.close();
    }
    public static void AllWord(String user) throws IOException {
       /* boolean quit = true;
        do {*/
            File fileE = new File("./study/English.txt"); //链接单词
            FileInputStream InEnglish = new FileInputStream(fileE); //链接单词
            File fileC = new File("./study/Chinese.txt"); //链接释义
            FileInputStream InChinese = new FileInputStream(fileC); //链接中文释义


//            Scanner scanner = new Scanner(System.in);
//            System.out.print("请选择\n直接进入（Enter）\n输入新单词(input)\n退出请按输入(exit)：");

//            String user = scanner.nextLine();
         System.out.println("user:"+user);
            if("exit".equalsIgnoreCase(user)){
                System.out.println("欢迎下次再来！！！");
                System.out.println(user);
//                quit =false;

            }
            else if ("Enter".equalsIgnoreCase(user)) { //忽略大小写对比
              //如果选择手动输入新单词
            } else if ("input".equalsIgnoreCase(user)) {
//            File fileE1 = new File("./study/English.txt");
                FileOutputStream OutEnglish = new FileOutputStream("./study/English.txt", true);
//                File fileC1 = new File("./study/English.txt");
                FileOutputStream OutChinese = new FileOutputStream("./study/Chinese.txt", true);
                Scanner scanner1 = new Scanner(System.in);
                //编辑状态

                while (true) {
                    System.out.print("请输入单词：");
                    String word1 = scanner1.nextLine();
                    if ("q".equals(word1)) {
                        System.out.println("已退出编辑状态！");
                        break;
                    } else {
                        OutEnglish.write(word1.getBytes(StandardCharsets.UTF_8));
                        OutEnglish.write(",".getBytes(StandardCharsets.UTF_8));
                        System.out.println("已存入单词数据库！");
                    }
                    /**
                     * 开始输入中文
                     */
                    while (true) {
                        System.out.print("请输入" + word1 + "的中文释义：");
                        String word2 = scanner1.nextLine();
                        String zone = "[a-zA-Z0-9_]+"; //正则表达式判断----------- zone：区域
                        boolean match = word2.matches(zone);
                        if (!match) {
                            OutChinese.write(word2.getBytes(StandardCharsets.UTF_8));
                            OutChinese.write("，".getBytes(StandardCharsets.UTF_8));
                            System.out.println("已存入中文释义数据库！");

                            break;
                        } else {
                            System.out.println("请不要输入奇奇怪怪的例如：字符字母数字！！！");
                            continue;
                        }
                    }
                }
            }
//        } while (quit);

    }


    public static String JF()throws IOException{
         //返回值，参数
        /**
         * 创建窗口及面板
         */
        JFrame win = new JFrame();
        JPanel panel = new JPanel(null);
        win.setSize(650,230);
        /**
         *创建文本框
         */
        JTextArea sourceE = new JTextArea("请选择\n直接进入（Enter）\n输入新单词(input)\n退出请按输入(exit)：");
        sourceE.setFont(new Font("宋体",Font.BOLD,20));//设置文本框字体格式

        JTextArea sourceC = new JTextArea();
        /**
         *文本框位置
         */
        sourceE.setLocation(10,70);
        sourceC.setLocation(320,70);
        /**
         *文本框大小
         */
        sourceE.setSize(300,100);
        sourceC.setSize(300,100);
        /**
         *设置换行
         */
        sourceE.setLineWrap(true);
        sourceC.setLineWrap(true);
        /**
         *按钮:进入，输入，退出，保存
         */
        JButton buttonEnter =new JButton("Enter");
        JButton buttonInput =new JButton("Input");
        JButton buttonExit =new JButton("Exit");
        JButton buttonSave =new JButton("Save");
        /**
         *按钮参数：位置，尺寸
         */
        //位置
        buttonEnter.setLocation(50,10);
        buttonInput.setLocation(200,10);
        buttonExit.setLocation(500,10);
        buttonSave.setLocation(350,10);
        //大小
        buttonEnter.setSize(90,50);
        buttonInput.setSize(90,50);
        buttonExit.setSize(90,50);
        buttonSave.setSize(90,50);
        //按钮字体---------------------------------------------------btn1.setPreferredSize( new Dimension(120,60));
        Font font = new Font("黑体",Font.BOLD,20);//设置黑体  粗体
        buttonEnter.setFont(font);  //设置新字体
        buttonInput.setFont(font);  //设置新字体
        buttonSave.setFont(font);  //设置新字体
        buttonExit.setFont(font);  //设置新字体

 /*
    way2
    文本框的基本属性
*/
        /*

            // 括号里为整数则为文本框的默认长，括号里为字符串则默认显示字符串
            JTextField j_tf=new JTextField("默认初始显示的字符串");// 文本框里初始字符
            j_tf.setColumns(30);// 30个字符的宽
            //j_tf.setText("这也是 “默认初始显示的字符串”");// 默认初始显示的字符串
            j_tf.setFont(new Font("宋体",Font.BOLD,20));// 黑体，加粗，20个字符长度
//        c.add(j_tf);

            JButton btn=new JButton("点击触发事件");
            // Action(动作)，performed(执行)，event（事件）
            btn.addActionListener(new ActionListener(){// 动作监听
                public void actionPerformed(ActionEvent e){// 事件
                    // 弹出对话框option(选择)，message(信息)，dialog（对话框）
                    JOptionPane.showMessageDialog(win,"文本框中的内容：\n    "+j_tf.getText());// 获取文本框中的文本值
                    j_tf.setText("");// 清空文本框
                    j_tf.requestFocus();// 获取焦点（光标）。reques（要求），focus（聚焦）
                }

            });
//            c.add(btn);
*/
 /*       public class WinTest7{    public static void main(String[] args)    {
            JFrame frame = new JFrame();
            JTextArea area = new JTextArea("welcom to textarea!");
            area.setText("this is new default String");
            frame.add(area);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
            frame.setLayout(new FlowLayout());
            frame.setVisible(true);    }}*/

        /**
         * 面板添加组件
         */
        //添加按钮
        panel.add(buttonEnter);
        panel.add(buttonInput);
        panel.add(buttonExit);
        panel.add(buttonSave);
        //添加文本框
        panel.add(sourceE);
        panel.add(sourceC);
        //窗口添加面板
        win.add(panel);
        win.setLocationRelativeTo(null);//窗口居中
        win.setVisible(true);//显示窗口
        win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//退出时关闭程序
        System.out.println(parameter);
       return parameter;
    }
    //主方法
    public static void main(String[] args) throws IOException {
       /* String BT=JF();
        AllWord(BT);*/
//        EnterBT();
//        ChineseWr();
        //      Enter点击事件
        JF();
        /*buttonEnter.addActionListener(e -> {
            System.out.println("Enter");
            try {
                EnterBT();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
//            parameter = "Enter";
         *//*   try {
                AllWord(parameter);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }*/
        /*

        });
//      编辑点击事件
        buttonInput.addActionListener(e -> {
//            System.out.println("exit");
//            parameter = "Enter";
            try {
                ChineseWr();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });
//      保存点击事件
        buttonSave.addActionListener(e -> {
           *//* System.out.println("save");
            parameter = "Enter";*//*
            try {
                FileSave();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }

        });
//      退出点击事件
        buttonExit.addActionListener(e -> {
            System.out.println("已退出");
            parameter = "Enter";
            win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    //此行是重点
            win.setVisible(false);
        });
//        FileSave();*/
    }


}
